$(function () {
    $('.nav>li').click(function () {
        $(this).addClass('active').siblings().removeClass('active')
        $('.box>li').removeClass('active').eq($(this).index()).addClass('active')
        switch ($(this).index()) {
            case 0: getUserList(); break;
            case 1: getBannerList(); break
        }
    })
    const token = window.sessionStorage.getItem('token')
    const id = window.sessionStorage.getItem('id')
    testLogin()
    async function testLogin() {

        if (!token || !id) return window.location.href = './login.html'

        const res = await $.ajax({
            url: 'http://localhost:8080/users/info/' + id,
            // data: { id },
            headers: { authorization: token }

        })
        // const res = await $.ajax({
        //     url: 'http://localhost:8080/users/info/' + id,
        //     headers: { authorization: token }
        //   })
        console.log(res);

        if (res.code === 1) {
            init()
            $('.nickname').text(res.info.nickname)
            return
        }
        window.location.href = './login.html'
    }
    function init() {
        getUserList()
    }
    async function getBannerList() {
        const res = await $.ajax({
            url: 'http://localhost:8080/banner/list',
            headers: { authorization: token }
        })
        console.log(res);
        $('.banner_list > tbody').html(template('list_template', { list: res.list }))

    }
    $('.banner>form input[type=file]').on('change', function () {
        const fileInfo = this.files[0]

        if (!fileInfo) return

        if (fileInfo.type.split('/')[0] !== 'image') return this.value = ''
        const fr = new FileReader()
        fr.readAsDataURL(fileInfo)

        fr.onload = (res) => {
            console.log(res);
            $(this).prev().css('background-image', `url(${res.currentTarget.result})`)
        }

    })
    $('.banner >.add').on('submit', async e => {
        e.preventDefault()
        const fm = new FormData($('form')[0])
        const res = await $.ajax({
            url: 'http://localhost:8080/banner/add',
            data: fm,
            method: 'put',
            headers: { authorization: token },
            contentType: false,
            processData: false
        })
        console.log(res);
        if (res.code === 0) return alert(res.massage)

        if (res.code === 1) {
            alert('添加成功')
            getBannerList()
            $('form')[0].reset()
            $('.banner .add .show div')[0].style.backgroundImage = ''
        }
    })
    $('.banner table').on('click', '.del', async function () {
        if (!window.confirm('您确定删除该内容吗')) return
        const res = await $.ajax({
            url: 'http://localhost:8080/banner/remove/' + this.dataset.id,
            method: "delete",
            headers: { authorization: token }
        })
        if (res.code === 0) return alert(res.massage)
        if (res.code === 1) {
            alert(res.massage)
            getBannerList()


        }
    })
    $('.banner table').on('click', '.edit', async function () {
        const res = await $.ajax({
            url: 'http://localhost:8080/banner/info/' + this.dataset.id,
            method: 'get',
            headers: { authorization: token }
        })
        if (res.code !== 1) return

        $('.banner .edit .title').val(res.info.title)
        $('.banner .edit .link').val(res.info.link)
        $('.banner>.edit>.show div').css('background-image', `url(http://localhost:8080${res.info.img_url})`)
        $('.banner>.edit>.update').attr('data-id', `${res.info.id}`)
        $('.banner>.edit').show()
        $('.banner>.add').hide()
    })
    $('.banner >.edit .cancel').on('click', () => {
        $('.banner >.edit')[0].reset()
        $('.banner>.edit').hide()
        $('.banner>.add').show()
    })

    $('.banner > .edit').on('submit', async e => {
        e.preventDefault()

        // 利用 FormData 获取表单信息
        const fm = new FormData($('.banner > .edit')[0])

        // 补充一个 id 信息
        fm.append('id', $('.banner > .edit .update')[0].dataset.id)
        console.log(fm);
        // console.log($('.banner > .edit')[0]);
        // 发送 ajax 上传
        const res = await $.ajax({
            url: 'http://localhost:8080/banner/update',
            method: 'PATCH',
            data: fm,
            processData: false,
            contentType: false,
            headers: { authorization: token }
        })
        console.log(res);
        if (res.code === 0) return alert(res.message)

        if (res.code === 1) {
            alert('修改轮播图成功')
            getBannerList()
            $('.banner > .edit .cancel').trigger('click')
            $('.banner .add .show div')[0].style.backgroundImage = ''
        }
    })
    const list_info = {
        current: 1,
        pagesize: 5,
        is_status: 'all',
        gender: 'all',
        search: ''
    }
    async function getUserList() {
        const res = await $.ajax({
            url: 'http://localhost:8080/person/list',
            headers: { authorization: token },
            data: list_info
        })
        console.log(res);
        $('.users tbody').html(template('users_template', { list: res.list }))


        $('.users .pagination').html(template('users_pagination', { list_info, list: res.list, total: res.totalPage }))

        $('.users .filter_box').html(template('users_filter', { list_info }))
    }
    $('.users .pagination').on('click', e => {
        const t = e.target

        if (t.className === 'next') {
            list_info.current++
            getUserList()
        }
        if (t.className === 'prev') {
            list_info.current--
            getUserList()
        }

        if (t.className === 'first') {
            list_info.current = 1
            getUserList()
        }
        if (t.className === 'last') {
            list_info.current = t.dataset.total - 0
            getUserList()
        }
        if (t.className == 'item') {
            list_info.current = t.innerText - 0
            getUserList()
        }
        if (t.className === 'go') {
            let page = $(t).prev().val() - 0

            if (isNaN(page)) page = 1
            if (page <= 1) page = 1
            if (page >= t.dataset.total - 0) page = t.dataset.total - 0
            page = parseInt(page)

            list_info.current = page
            getUserList()
        }
    })
    $('.users .filter_box').on('click', 'button', () => {
        list_info.search = $('.users .filter_box').find('.search').val()
        list_info.gender = $('.users .filter_box').find('.gender').val()
        list_info.is_status = $('.users .filter_box').find('.status').val()
        list_info.pagesize = $('.users .filter_box').find('.pagesize').val() - 0

        getUserList()
    })
    $('.users table tbody').on('change', 'select', async function () {
        // 拿到药修改的用户 id 和 状态
        const id = this.dataset.id
        const status = this.value === '启用' ? 1 : 0
        console.log(status);
        // 发送请求
        const res = await $.ajax({
            url: 'http://localhost:8080/person/status',
            method: 'PATCH',
            data: { id, status },
            headers: { authorization: token }
        })
        console.log(res);
        // 判断操作
        // if (res.code === 1) return alert(res.message)
    })
    $('.users table tbody').on('click', 'button', async function (e) {
        const t = e.target
        const id = this.dataset.id
        if (t.className === 'reset') {

            await $.ajax({
                url: 'http://localhost:8080/person/reset',
                method: 'PATCH',
                data: { id },
                headers: { authorization: token }
            })
            getUserList()
        }
        if (t.className === 'del') {

            await $.ajax({
                url: 'http://localhost:8080/person/del',
                method: 'delete',
                data: { id },
                headers: { authorization: token }
            })
            getUserList()
        }
        if (t.className === 'edit') {
            console.log(id);

            window.sessionStorage.setItem('user_id', id)
            window.location.href = './self.html'
        }
    })
    $('.content .box .users .add').on('click', 'button', (e) => {
        window.location.href='./register.html'
    })
})